package com.cloudm.technician.ui.modules.cloudm_box.device_detail

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.view.View
import com.bigkoo.pickerview.TimePickerView
import com.cloudm.technician.R
import com.cloudm.technician.data.model.DeviceInfo
import com.cloudm.technician.data.model.MachineInfo
import com.cloudm.technician.extensions.dateToString
import com.cloudm.technician.extensions.openActivity
import com.cloudm.technician.extensions.string
import com.cloudm.technician.extensions.toast
import com.cloudm.technician.ui.base.BasePermissionsFragment
import com.cloudm.technician.ui.modules.cloudm_box.device_debug.DeviceDebugActivity
import com.cloudm.technician.ui.modules.cloudm_box.machine.MachineActivity
import com.cloudm.technician.ui.modules.scan_qr_code.ScanQrCodeActivity
import com.cloudm.technician.ui.widget.OnceClickListener
import kotlinx.android.synthetic.main.fragment_device_detail.*
import java.util.*

/**
 * 作者: wesley
 * 时间: 2017/12/19
 * 描述: ui
 */
class DeviceDetailFragment : BasePermissionsFragment<DeviceDetailPresenter>(),
        DeviceDetailContract.View {

    private var flag: Int = 0
    private var info: DeviceInfo? = null
    var listener: OnTitleReceiveListener? = null
    private var machineTypeId = -1
    private var machineBrandId = -1
    private var machineModelId = -1
    private var deviceId = -1

    override val resource: Int
        get() = R.layout.fragment_device_detail

    companion object {
        private const val TAG = "DeviceDetailFragment"
        private const val REQUEST_CODE_MACHINE_TYPE = 1
        private const val REQUEST_CODE_MACHINE_BRAND = 2
        private const val REQUEST_CODE_MACHIEN_MODEL = 3
        private const val REQUEST_CODE_PERMISSION_FOR_CAMERA = 4
        private const val FLAG = "flag"
        private const val INFO = "info"
        fun newInstance(flag: Int, info: DeviceInfo?) = DeviceDetailFragment().apply {
            arguments = Bundle().apply {
                putInt(FLAG, flag)
                putParcelable(INFO, info)
            }
        }
    }

    override fun initInject() {
        DaggerDeviceDetailComponent.builder().appComponent(
                appComponent).deviceDetailPresenterModule(
                DeviceDetailPresenterModule(this)).build().inject(this)
    }

    override fun handleBundle(bundle: Bundle) {
        flag = bundle.getInt(FLAG)
        info = bundle.getParcelable(INFO)
    }

    override fun initVariables() {

    }

    override fun initViews(view: View) {
        presenter?.buildTitle(flag)
    }

    override fun initListener() {
        rlPlateNumber.setOnClickListener(ItemClickListener())
        rlMachineType.setOnClickListener(ItemClickListener())
        rlMachineBrand.setOnClickListener(ItemClickListener())
        rlMachineModel.setOnClickListener(ItemClickListener())
        rlMachineFactory.setOnClickListener(ItemClickListener())
        llScanPlateNumber.setOnClickListener(ItemClickListener())
    }

    override fun onAddMachineTitleReceive() {
        listener?.onTitleReceive(mContext.resources.getString(R.string.add_machine))
    }

    override fun onBasicMsgTitleReceive() {
        listener?.onTitleReceive(mContext.resources.getString(R.string.basic_message))
    }

    override fun initUi() {
        info?.let {
            deviceId = it.id ?: -1
            machineTypeId = it.typeId ?: -1
            machineBrandId = it.brandId ?: -1
            machineModelId = it.modelId ?: -1
            tvPlateNumberValue.text = it.license
            etMachineName.setText(it.deviceName)
            tvMachineTypeValue.text = it.type
            tvMachineBrandValue.text = it.brand
            tvMachineModelValue.text = it.model
            etMachineNumbers.setText(it.rackId)
            etMachineWorkTime.setText(it.workTime)
            tvMachineFactoryValue.text = it.factoryTime
        }
    }


    override fun showAddDeviceDialog() {
        showLoadingDialog(mContext.resources.getString(R.string.device_adding))
    }

    override fun showEditDeviceDialog() {
        showLoadingDialog(mContext.resources.getString(R.string.device_editing))
    }

    override fun hideDeviceDialog() {
        hideLoadingDialog()
    }

    fun nextStep() {
        presenter?.addOrModifyDevice(flag, machineTypeId, machineBrandId, machineModelId, deviceId,
                info)
    }

    fun showHintDialog() {
        showPromptDialog(R.string.make_sure_exit_edit)
    }

    override fun onPositiveButtonClick() {
        val activity = mContext as? DeviceDetailActivity ?: return
        activity.finish()
    }


    interface OnTitleReceiveListener {
        fun onTitleReceive(title: String)
    }

    //点击事件
    private inner class ItemClickListener : OnceClickListener() {
        override fun onOnceClick(view: View) {
            when (view.id) {
                R.id.rlPlateNumber -> requestPermissionsForScanQrCode()
                R.id.rlMachineType -> openMachineActivity(0, REQUEST_CODE_MACHINE_TYPE)
                R.id.rlMachineBrand -> presenter?.openMachineBrandActivity(machineTypeId)
                R.id.rlMachineModel -> presenter?.openMachineModelActivity(machineTypeId,
                        machineBrandId)
                R.id.rlMachineFactory -> {
                    hideSoftKeyboard()
                    showPickerView()
                }
                R.id.llScanPlateNumber -> showQrCodeDialog()
                else -> {

                }
            }
        }
    }

    override fun openMachineBrandActivity() {
        openMachineActivity(1, REQUEST_CODE_MACHINE_BRAND)
    }

    override fun openMachineModelActivity() {
        openMachineActivity(2, REQUEST_CODE_MACHIEN_MODEL)
    }

    override fun showMachineBrandMsg() {
        mContext.toast(mContext.resources.getString(R.string.please_select_machine_brand))
    }

    override fun showMachineTypeMsg() {
        mContext.toast(mContext.resources.getString(R.string.please_select_machine_type))
    }

    override fun showMachineModelMsg() {
        mContext.toast(mContext.resources.getString(R.string.please_select_machine_model))
    }

    override fun showLicenseEmpMsg() {
        mContext.toast(mContext.resources.getString(R.string.license_can_not_empty))
    }

    override fun showDeviceNameEmpMsg() {
        mContext.toast(mContext.resources.getString(R.string.device_name_can_not_empty))
    }

    override fun showDeviceNameContainsBlankMsg() {
        mContext.toast(mContext.resources.getString(R.string.device_name_can_not_contains_blank))
    }

    override fun showRackEmpMsg() {
        mContext.toast(mContext.resources.getString(R.string.please_input_machine_number))
    }

    override fun showRackFormatErrMsg() {
        mContext.toast(mContext.resources.getString(R.string.rack_format_error))
    }

    override fun showWorkTimeMsg() {
        mContext.toast(mContext.resources.getString(R.string.please_input_machine_work_time))
    }

    override fun showFactoryTimeMsg() {
        mContext.toast(mContext.resources.getString(R.string.please_select_machine_factory))
    }

    override fun showScanResultEmpMsg() {
        mContext.toast(mContext.resources.getString(R.string.scan_result_is_null))
    }

    override fun showLicenseFormatMsg() {
        mContext.toast(mContext.resources.getString(R.string.license_format_error))
    }


    override fun showRightLicense(license: String) {
        tvPlateNumberValue.text = license
    }

    override fun showDeviceEmpMsg() {
        mContext.toast(mContext.resources.getString(R.string.edit_error_device_info_is_null))
    }

    override fun getLicense(): String? = tvPlateNumberValue.text.toString()

    override fun getDeviceName(): String? = etMachineName.string()

    override fun getRackId(): String? = etMachineNumbers.string()

    override fun getWorkTime(): String? = etMachineWorkTime.string()

    override fun getFactoryTime(): String? = tvMachineFactoryValue.text.toString()

    override fun addDeviceSuccess(info: DeviceInfo?) {
        deviceId = info?.id ?: -1
        flag = 1
        val intent = Intent(mContext, DeviceDebugActivity::class.java).apply {
            putExtras(Bundle().apply {
                putParcelable("info", info)
            })
        }
        mContext.openActivity(intent)
    }

    override fun editDeviceSuccess(info: DeviceInfo) {
        openActivityByStatus(info, true)
    }

    override fun showErrorMsg(msg: String) {
        mContext.toast(msg)
    }

    private fun openMachineActivity(flag: Int, requestCode: Int) {
        val intent = Intent(mContext, MachineActivity::class.java).apply {
            putExtras(Bundle().apply {
                putInt("flag", flag)
                putInt("typeId", machineTypeId)
                putInt("brandId", machineBrandId)
                putInt("modelId", machineModelId)
            })
        }
        startActivityForResult(intent, requestCode)
    }


    private fun showPickerView() {
        val selectedDate = Calendar.getInstance()
        val startDate = Calendar.getInstance()
        startDate.set(1900, 0, 1)
        val pvTime = TimePickerView.Builder(context,
                TimePickerView.OnTimeSelectListener { date, _ ->
                    tvMachineFactoryValue.text = date?.dateToString()
                }).setTitleText(mContext.resources.getString(R.string.select_time)).setSubmitColor(
                ContextCompat.getColor(mContext, R.color.colorPrimary)).setCancelColor(
                ContextCompat.getColor(mContext, R.color.colorPrimary)).setCancelText(
                mContext.resources.getString(R.string.cancel)).setType(
                booleanArrayOf(true, true, true, false, false, false)).isCyclic(true).isCenterLabel(
                false).setRangDate(startDate, selectedDate).setSubmitText(
                mContext.resources.getString(R.string.ok)).build()
        pvTime.setDate(Calendar.getInstance())
        pvTime.show()
    }


    private fun showQrCodeDialog() {
        val fragment = DeviceDetailQrCodeDialogFragment.newInstance()
        fragment.show(childFragmentManager, TAG)
    }

    override fun scanRrCodeGrantedSuccess() {
        super.scanRrCodeGrantedSuccess()
        val intent = Intent(mContext, ScanQrCodeActivity::class.java).apply {
            putExtras(Bundle().apply {
                putInt("flag", 0)
            })
        }
        startActivityForResult(intent, REQUEST_CODE_PERMISSION_FOR_CAMERA)
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) {
            return
        }
        when (requestCode) {
            REQUEST_CODE_MACHINE_TYPE -> {
                val info: MachineInfo? = data?.extras?.getParcelable("info")
                info?.let {
                    machineTypeId = it.id
                    machineBrandId = -1
                    machineModelId = -1
                    tvMachineTypeValue.text = it.name
                    tvMachineBrandValue.text = ""
                    tvMachineModelValue.text = ""
                }
            }

            REQUEST_CODE_MACHINE_BRAND -> {
                val info: MachineInfo? = data?.extras?.getParcelable("info")
                info?.let {
                    machineBrandId = it.id
                    machineModelId = -1
                    tvMachineBrandValue.text = it.name
                    tvMachineModelValue.text = ""
                }
            }

            REQUEST_CODE_MACHIEN_MODEL -> {
                val info: MachineInfo? = data?.extras?.getParcelable("info")
                info?.let {
                    machineModelId = it.id
                    tvMachineModelValue.text = it.modelName
                }
            }

            REQUEST_CODE_PERMISSION_FOR_CAMERA -> {
                presenter?.dealWithScanResult(data?.extras?.getString("result"))
            }
        }
    }
}